# 封装接口请求
import requests
from Lib.common.common_function import *
import jsonpath
import json


class RequestClass:

    def __init__(self, host: str, method: str):
        '''
        :param host: 需要访问的主机接口地址
        :param method: 请求的方法
        '''
        self.method = method
        self.host = host

    def request(self, params: dict):
        '''
        发送请求
        :param params: 请求参数 包含 url headers data(请求参数)
        :return:
        '''
        url = self.host + params['url']
        if self.method == "post":
            if params['headers'] is not None:
                if 'Content-Type' not in params['headers']:
                    res = requests.post(url=url, headers=params['headers'], json=params['data'])
                    print(params['data'])
                    print(url)
                    print(res)
                    print(res.request.body)
                    print(res.request.headers)
                    print(res.text)
                    return res.text
                else:
                    res = requests.post(url=url, headers=params['headers'], data=params['data']).text
                    print(params['data'])
                    print(url)
                    print(res)
                    print(res.request.body)
                    print(res.request.headers)
                    print(res.text)
                    return res
            else:
                res = requests.post(url=url, json=params['data'])
                print(params['data'])
                print(url)
                print(res)
                print(res.request.body)
                print(res.request.headers)
                print(res.text)
                return res.text
        if self.method == "get":
            return requests.get(url=url, headers=params['headers'], data=params['data']).text

    def get_value_interface(self, params: dict, keyword: str):
        '''
        获取接口返回的值
        :param params:  请求参数
        :param keyword: 需要获取的值的关键字
        :return:
        '''
        res = json.loads(self.request(params))
        values = jsonpath.jsonpath(res, f'$..{keyword}')
        if values:
            if len(values) == 1:
                return values[0]
            else:
                return values


if __name__ == '__main__':
    request = RequestClass('SIT_HOST_82', 'get')
    print(request.host)
    print(request.method)
